package com.hui.config.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.hui.config.security.constant.AuthError;
import com.hui.config.security.utils.CrosUtil;
import com.hui.dto.JsonResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败之后的处理,或者没有拦截处理的请求会到这里
 */
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        JsonResult jsonResult = new JsonResult();
        CrosUtil.crosOrgin(request, response);
        if (exception instanceof UsernameNotFoundException) {
            jsonResult.setCode(AuthError.TOKEN_AUTH_ERROR.code);
            jsonResult.setMsg(AuthError.TOKEN_AUTH_ERROR.msg);
            response.getWriter().write(JSONObject.toJSONString(jsonResult));
        } else if (exception instanceof BadCredentialsException) {
            jsonResult.setCode(AuthError.TOKEN_AUTH_ERROR.code);
            jsonResult.setMsg(AuthError.TOKEN_AUTH_ERROR.msg);
            response.getWriter().write(JSONObject.toJSONString(jsonResult));
        }
    }
}
